(function(){

function showAlert(msg, cls) {
  const old = document.querySelector('.alert')
  if (old) {
    document.body.removeChild(old)
  }

  const alert = document.createElement('div')
  alert.className = 'alert ' + cls
  alert.innerText = msg
  document.body.appendChild(alert)
}

function sizeToString(size) {
  const K = 1024
  const M = K * 1024
  const G = M * 1024

  if (size >= G) {
    return `${(size / G).toFixed(1)} GB`
  }

  if (size >= M) {
    return `${(size / M).toFixed(1)} MB`
  }

  if (size >= K) {
    return `${(size / K).toFixed(1)} KB`
  }

  return `${size} B`
}

function createTable(cols, data) {
  const table = document.createElement('table')

  const tr = document.createElement('tr')
  for (const col of cols) {
    const th = document.createElement('th')
    th.innerText = col.label
    tr.appendChild(th)
  }
  table.appendChild(tr)

  for (const row of data) {
    const tr = document.createElement('tr')
    for (const col of cols) {
      const td = document.createElement('td')
      if (col.button) {
        const button = document.createElement('button')
        button.innerText = col.button
        button.onclick = () => col.action(row)
        td.appendChild(button)
      } else {
        td.innerText = row[col.prop]
      }
      tr.appendChild(td)
    }
    table.appendChild(tr)
  }

  return table
}

function downloadFile(file) {
  const [len, name] = file
  __TAURI__.dialog.save({
    defaultPath: name
  }).then(path => {
    if (path) {
      __TAURI__.invoke('download_file', { name, len, path })
    }
  })
}

function uploadFile(file) {
  const [len, name] = file
  __TAURI__.dialog.open().then(path => {
    if (path) {
      __TAURI__.invoke('upload_file', { name, offset: len, path })
    }
  })
}

oncontextmenu = e => e.preventDefault()

const viewLogin = document.getElementById('view-login')
const formLogin = document.getElementById('form-login')
const btnRegister = document.getElementById('btn-register')
const btnLogin = document.getElementById('btn-login')
const viewMain = document.getElementById('view-main')
const viewContainer = document.getElementById('view-container')
const btnDisconnect = document.getElementById('btn-disconnect')
const btnListFull = document.getElementById('btn-list-full')
const btnListPart = document.getElementById('btn-list-part')
const btnUpload = document.getElementById('btn-upload')

btnRegister.onclick = () => __TAURI__.invoke('connect', {
  host: formLogin.elements.host.value,
  username: formLogin.elements.username.value,
  password: formLogin.elements.password.value,
  register: true
})

btnLogin.onclick = () => __TAURI__.invoke('connect', {
  host: formLogin.elements.host.value,
  username: formLogin.elements.username.value,
  password: formLogin.elements.password.value,
  register: false
})

btnDisconnect.onclick = () => __TAURI__.invoke('disconnect')

btnListFull.onclick = () => __TAURI__.invoke('fetch_list', { part: false })

btnListPart.onclick = () => __TAURI__.invoke('fetch_list', { part: true })

btnUpload.onclick = () => {
  __TAURI__.dialog.open().then(path => {
    if (path) {
      __TAURI__.invoke('upload_file', { name: null, offset: null, path })
    }
  })
}

__TAURI__.event.listen('connect', () => {
  formLogin.reset()

  viewLogin.style.display = 'none'
  viewMain.style.display = ''

  __TAURI__.invoke('fetch_list', { part: false })
})

__TAURI__.event.listen('disconnect', () => {
  viewContainer.innerHTML = ''

  viewLogin.style.display = ''
  viewMain.style.display = 'none'
})

__TAURI__.event.listen('list', e => {
  viewContainer.innerHTML = ''

  const [part, list] = e.payload
  list.forEach(i => i.lenDisplay = sizeToString(i[0]))

  viewContainer.appendChild(createTable([
    { label: '文件名', prop: 1 },
    { label: part ? '已上传' : '大小', prop: 'lenDisplay' },
    {
      label: '操作',
      button: part ? '继续上传' : '下载',
      action: part ? uploadFile : downloadFile
    }
  ], list))
})

__TAURI__.event.listen('downloaded', e => showAlert(`File '${e.payload}' downloaded successfully`, 'success'))

__TAURI__.event.listen('uploaded', e => {
  showAlert(`File '${e.payload}' uploaded successfully`, 'success')
  __TAURI__.invoke('fetch_list', { part: false })
})

__TAURI__.event.listen('error', e => showAlert(e.payload, 'error'))

}())
